/*
 *  Copyright 2019-2020 Zheng Jie
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package me.zhengjie.modules.biz.rest;

import cn.hutool.core.convert.Convert;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import me.zhengjie.annotation.AnonymousAccess;
import me.zhengjie.annotation.Log;
import me.zhengjie.modules.biz.domain.StorehouseOrder;
import me.zhengjie.modules.biz.service.StorehouseOrderService;
import me.zhengjie.modules.biz.service.dto.StorehouseOrderQueryCriteria;
import me.zhengjie.modules.utils.BaseResult;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Admin
 * @website https://eladmin.vip
 * @date 2023-03-13
 **/

@RestController
@RequiredArgsConstructor
@Api(tags = "storehouse-order管理")
@RequestMapping("/api/storehouseOrder")
public class StorehouseOrderController {

    private final StorehouseOrderService storehouseOrderService;

    @Log("导出数据")
    @ApiOperation("导出数据")
    @GetMapping(value = "/recordList/download")
//    @PreAuthorize("@el.check('storehouseOrder:list')")
    public void exportStorehouseOrder(HttpServletResponse response, StorehouseOrderQueryCriteria criteria) throws IOException {
        storehouseOrderService.download(storehouseOrderService.recordList(criteria), response);
    }

    @GetMapping
    @Log("查询storehouse-order")
    @ApiOperation("查询storehouse-order")
//    @PreAuthorize("@el.check('storehouseOrder:list')")
    public ResponseEntity<Object> queryStorehouseOrder(StorehouseOrderQueryCriteria criteria, Pageable pageable) {
        return new ResponseEntity<>(storehouseOrderService.queryAll(criteria, pageable), HttpStatus.OK);
    }

    @PostMapping
    @Log("新增storehouse-order")
    @ApiOperation("新增storehouse-order")
//    @PreAuthorize("@el.check('storehouseOrder:add')")
    public ResponseEntity<Object> createStorehouseOrder(@Validated @RequestBody StorehouseOrder resources) {
        return new ResponseEntity<>(storehouseOrderService.create(resources), HttpStatus.CREATED);
    }

    @PutMapping
    @Log("修改storehouse-order")
    @ApiOperation("修改storehouse-order")
//    @PreAuthorize("@el.check('storehouseOrder:edit')")
    public ResponseEntity<Object> updateStorehouseOrder(@Validated @RequestBody StorehouseOrder resources) {
        storehouseOrderService.update(resources);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    @DeleteMapping
    @Log("删除storehouse-order")
    @ApiOperation("删除storehouse-order")
//    @PreAuthorize("@el.check('storehouseOrder:del')")
    public ResponseEntity<Object> deleteStorehouseOrder(@RequestBody Integer[] ids) {
        storehouseOrderService.deleteAll(ids);
        return new ResponseEntity<>(HttpStatus.OK);
    }

    @PostMapping("/create")
    @ApiOperation("创建订单")
    @Log("创建订单")
    @AnonymousAccess
    public ResponseEntity<Object> createOrder(@RequestBody Map<String, Object> data) {
        return new ResponseEntity<>(storehouseOrderService.createOrder(
                Convert.toStr(data.get("note")),
                Convert.toStr(data.get("data"))
        ), HttpStatus.OK);
    }


    @PostMapping("/audit")
    @ApiOperation("审核")
    @Log("审核")
    public ResponseEntity<Object> audit(int id, int auditValue, String note) {
        storehouseOrderService.auditOrder(id, auditValue, note);
        return new ResponseEntity<>(HttpStatus.OK);
    }

    @GetMapping("/auditList")
    @ApiOperation("审核列表")
    public ResponseEntity<Object> auditList(StorehouseOrderQueryCriteria criteria, Pageable pageable) {
        return new ResponseEntity<>(storehouseOrderService.auditOrderList(criteria, pageable), HttpStatus.OK);
    }

    @GetMapping("/auditPersonalList")
    @ApiOperation("个人审核列表")
    @AnonymousAccess
    public ResponseEntity<Object> auditPersonalList(StorehouseOrderQueryCriteria criteria, Pageable pageable) {
        return new ResponseEntity<>(storehouseOrderService.auditOrderPersonalList(criteria, pageable), HttpStatus.OK);
    }

    @PostMapping("/delivery")
    @ApiOperation("出库/领用(先生成订单，再领取)")
    @AnonymousAccess
    @Log("出库/领用")
    public ResponseEntity<Object> delivery(@RequestBody Map<String, Object> data) throws Exception {
        Map<String, Object> map = storehouseOrderService.delivery(Convert.toInt(data.get("id")), Convert.toStr(data.get("data")));
        return new ResponseEntity<>(map, HttpStatus.OK);
    }

    @PostMapping("/delivery-v2")//给移动端使用
    @ApiOperation("出库/领用")
    @AnonymousAccess
    @Log("出库/领用-v2")
    public ResponseEntity<Object> deliveryV2(@RequestBody Map<String, Object> data) throws Exception {
        try {
            storehouseOrderService.delivery(Convert.toInt(data.get("id")), Convert.toStr(data.get("data")));
            return new ResponseEntity<>(new BaseResult(0, "成功", 1), HttpStatus.OK);
        } catch (Exception e) {
            return new ResponseEntity<>(new BaseResult(-1, e.getMessage()), HttpStatus.OK);
        }
    }


    @GetMapping("/deliveryList")
    @ApiOperation("待出库列表")
    @AnonymousAccess
    @Log("待出库列表")
    public ResponseEntity<Object> deliveryList(StorehouseOrderQueryCriteria criteria, Pageable pageable) {
        return new ResponseEntity<>(storehouseOrderService.deliveryList(criteria, pageable), HttpStatus.OK);
    }

    @GetMapping("/deliveryListAndroid")
    @AnonymousAccess
    @ApiOperation("待出库列表(安卓)")
    @Log("待出库列表(安卓)")
    public ResponseEntity<Object> deliveryListAndroid(String cabinetIds) {
        return new ResponseEntity<>(storehouseOrderService.deliveryListAndroid(cabinetIds), HttpStatus.OK);
    }


    @PostMapping("/cancel")
    @ApiOperation("取消")
    @AnonymousAccess
    @Log("取消")
    public ResponseEntity<Object> cancel(Integer id) {
        storehouseOrderService.cancelOrder(id);
        Map<String, Object> result = new HashMap<>();
        result.put("code", 0);
        result.put("msg", "取消成功");
        return new ResponseEntity<>(result, HttpStatus.OK);
    }

    @PostMapping("/delete")
    @ApiOperation("删除")
    @AnonymousAccess
    public ResponseEntity<Object> deleteOrder(Integer id) {
        storehouseOrderService.deleteByOrderId(id);
        return new ResponseEntity<>(HttpStatus.OK);
    }

    @GetMapping(value = "/recordList")
    @ApiOperation("记录列表")
    @Log("记录列表")
    @AnonymousAccess
    public ResponseEntity<Object> recordList(StorehouseOrderQueryCriteria criteria, Pageable pageable) {
        System.out.println("***************************");
        System.out.println("criteria.getId(): " + criteria.getId());
        System.out.println("criteria.getNo(): " + criteria.getNo());
        System.out.println("criteria.getStatus(): " + criteria.getStatus());
        System.out.println("criteria.getData(): " + criteria.getData());
        System.out.println("criteria.getUserId(): " + criteria.getUserId());
        System.out.println("criteria.getStore(): " + criteria.getStore());
        return new ResponseEntity<>(storehouseOrderService.recordList(criteria, pageable), HttpStatus.OK);
    }

    @PostMapping("/return")
    @ApiOperation("归还")
    @AnonymousAccess
    @Log("归还")
    public ResponseEntity<Object> giveBack(@RequestBody Map<String, Object> data) throws Exception {
        storehouseOrderService.giveBack(Convert.toInt(data.get("id")), Convert.toStr(data.get("data")));

        return new ResponseEntity<>(HttpStatus.OK);
    }

    @PostMapping("/return-v2")//给移动端使用的接口
    @ApiOperation("归还")
    @Log("归还-v2")
    @AnonymousAccess
    public ResponseEntity<Object> giveBackV2(@RequestBody Map<String, Object> data) {
        try {
            storehouseOrderService.giveBack(Convert.toInt(data.get("id")), Convert.toStr(data.get("data")));
            return new ResponseEntity<>(new BaseResult(0, "成功"), HttpStatus.OK);
        } catch (Exception e) {
            return new ResponseEntity<>(new BaseResult(-1, e.getMessage()), HttpStatus.OK);
        }
    }

    @GetMapping(value = "/returnList")
    @ApiOperation("记录列表")
    @Log("记录列表")
    @AnonymousAccess
    public ResponseEntity<Object> giveBackList(StorehouseOrderQueryCriteria criteria, Pageable pageable) {
        return new ResponseEntity<>(storehouseOrderService.giveBackList(criteria, pageable), HttpStatus.OK);
    }

    @GetMapping(value = "hcList")
    @AnonymousAccess
    public ResponseEntity<Object> hcList(Integer id, Integer cabinetId) {
        return new ResponseEntity<>(storehouseOrderService.hcList(id, cabinetId), HttpStatus.OK);
    }

    @PostMapping("/delivery-by-scan")//给移动端使用
    @ApiOperation("直接扫码登记领用")
    @AnonymousAccess
    @Log("直接扫码登记领用")
    public ResponseEntity<Object> deliveryByScan(int userId, @RequestParam List<Integer> hazardousChemicalsIds) {
        try {
            storehouseOrderService.deliveryByScan(userId, hazardousChemicalsIds);
            return new ResponseEntity<>(new BaseResult(0, "领取成功", 1), HttpStatus.OK);
        } catch (Exception e) {
            return new ResponseEntity<>(new BaseResult(-1, e.getMessage(), -1), HttpStatus.OK);
        }
    }

    @GetMapping("notReturnedListByUserId")
    @Log("根据用户ID查询订单")
    public BaseResult notReturnedListByUserId(Integer userId) {
        List<StorehouseOrder> orders = storehouseOrderService.findByUserIdAndStatus(userId, 5);

        return new BaseResult(0, "查询成功" + userId, orders);
    }

    @PostMapping("doReturn")
    @Log("归还物品接口")
    public BaseResult doReturn(
            Integer userId,
            Integer orderId,
            @RequestParam List<Integer> orderDetailIds,
            @RequestParam List<Integer> returnNumbers
    ) {
        try {
            storehouseOrderService.doReturn(userId, orderId, orderDetailIds, returnNumbers);

            return new BaseResult(0, "归还成功", 0);
        } catch (Exception e) {
            return new BaseResult(-1, e.getMessage(), -1);
        }
    }
}
